from core.models.product import Electronics, Clothing, Books, Home, Beauty, Food, Sports, Accessories
from core.services.data_manager import DataManager
from core.utils.logger import debug, info, warning, error
from core.utils.validators import validate_product

class ProductService:
    def __init__(self):
        self.data_manager = DataManager()
        self._create_sample_products()
    
    def _create_sample_products(self):
        products = self.get_all_products()
        if not products:
            sample_products = [
                Electronics(
                    product_id="p001",
                    name="Wireless Bluetooth Headphones",
                    price=299.0,
                    description="High quality wireless headphones with noise cancellation",
                    stock=50,
                    seller_id="seller_001",
                    brand="SoundMax",
                    warranty="1 year"
                ),
                Books(
                    product_id="p002", 
                    name="Python Programming Book",
                    price=59.0,
                    description="Complete Python programming tutorial for beginners",
                    stock=100,
                    seller_id="seller_002",
                    author="John Smith",
                    isbn="978-1234567890"
                ),
                Clothing(
                    product_id="p003",
                    name="Cotton T-Shirt",
                    price=89.0,
                    description="Comfortable cotton t-shirt, multiple colors available",
                    stock=200,
                    seller_id="seller_003",
                    size="M",
                    color="White"
                )
            ]
            
            products_data = [product.to_dict() for product in sample_products]
            self.data_manager.save_products(products_data)
    
    def get_all_products(self):
        products_data = self.data_manager.load_products()
        products = []
        
        for data in products_data:
            product = self._create_product_from_data(data)
            if product:
                products.append(product)
        
        return products
    
    def _create_product_from_data(self, data):
        category = data.get('category')
        image_path = data.get('image_path')
        name_en = data.get('name_en')
        description_en = data.get('description_en')
        
        if category == "electronics":
            return Electronics(
                data['product_id'],
                data['name'],
                data['price'],
                data['description'],
                data['stock'],
                data['seller_id'],
                data.get('brand', ''),
                data.get('warranty', ''),
                image_path,
                name_en,
                description_en
            )
        elif category == "clothing":
            return Clothing(
                data['product_id'],
                data['name'],
                data['price'],
                data['description'],
                data['stock'],
                data['seller_id'],
                data.get('size', ''),
                data.get('color', ''),
                image_path,
                name_en,
                description_en
            )
        elif category == "books":
            return Books(
                data['product_id'],
                data['name'],
                data['price'],
                data['description'],
                data['stock'],
                data['seller_id'],
                data.get('author', ''),
                data.get('isbn', ''),
                image_path,
                name_en,
                description_en
            )
        elif category == "home":
            return Home(
                data['product_id'],
                data['name'],
                data['price'],
                data['description'],
                data['stock'],
                data['seller_id'],
                data.get('brand', ''),
                data.get('material', ''),
                image_path,
                name_en,
                description_en
            )
        elif category == "beauty":
            return Beauty(
                data['product_id'],
                data['name'],
                data['price'],
                data['description'],
                data['stock'],
                data['seller_id'],
                data.get('brand', ''),
                data.get('origin', ''),
                image_path,
                name_en,
                description_en
            )
        elif category == "food":
            return Food(
                data['product_id'],
                data['name'],
                data['price'],
                data['description'],
                data['stock'],
                data['seller_id'],
                data.get('brand', ''),
                data.get('expiry_date', ''),
                image_path,
                name_en,
                description_en
            )
        elif category == "sports":
            return Sports(
                data['product_id'],
                data['name'],
                data['price'],
                data['description'],
                data['stock'],
                data['seller_id'],
                data.get('brand', ''),
                data.get('weight', ''),
                image_path,
                name_en,
                description_en
            )
        elif category == "accessories":
            return Accessories(
                data['product_id'],
                data['name'],
                data['price'],
                data['description'],
                data['stock'],
                data['seller_id'],
                data.get('brand', ''),
                data.get('compatible', ''),
                image_path,
                name_en,
                description_en
            )
        return None
    
    def get_product_by_id(self, product_id):
        """根据商品ID获取商品"""
        products = self.get_all_products()
        for product in products:
            if product.product_id == product_id:
                return product
        return None
    
    def update_stock(self, product_id, quantity_change):
        """更新商品库存
        
        Args:
            product_id: 商品ID
            quantity_change: 库存变化量（正数增加，负数减少）
        
        Returns:
            bool: 更新是否成功
        """
        products_data = self.data_manager.load_products()
        
        for product_data in products_data:
            if product_data['product_id'] == product_id:
                current_stock = product_data.get('stock', 0)
                new_stock = current_stock + quantity_change
                
                if new_stock < 0:
                    return False  # 库存不足
                
                product_data['stock'] = new_stock
                self.data_manager.save_products(products_data)
                return True
        
        return False  # 商品不存在
    
    def check_stock_availability(self, product_id, required_quantity):
        """检查商品库存是否足够
        
        Args:
            product_id: 商品ID
            required_quantity: 需要的数量
        
        Returns:
            bool: 库存是否足够
        """
        product = self.get_product_by_id(product_id)
        if not product:
            return False
        
        return product.stock >= required_quantity
    
    def get_stock_info(self, product_id):
        """获取商品库存信息
        
        Returns:
            dict: 包含库存信息的字典，如果商品不存在返回None
        """
        product = self.get_product_by_id(product_id)
        if not product:
            return None
        
        return {
            'product_id': product.product_id,
            'name': product.name,
            'current_stock': product.stock,
            'is_available': product.stock > 0,
            'is_low_stock': 0 < product.stock < 10
        }
    
    def validate_product_data(self, product_data):
        """验证商品数据"""
        is_valid, errors = validate_product(product_data)
        if not is_valid:
            error_msg = "; ".join(errors)
            warning(f"Product data validation failed: {product_data.get('name', 'Unknown')} - {error_msg}")
        return is_valid, errors
    
    def add_product(self, product_data):
        """添加新商品（带验证）"""
        # 验证商品数据
        is_valid, errors = self.validate_product_data(product_data)
        if not is_valid:
            raise ValueError("; ".join(errors))
        
        # 生成商品ID
        products = self.get_all_products()
        max_id = max([int(p.product_id[1:]) for p in products], default=0)
        product_id = f"p{max_id + 1:03d}"
        product_data['product_id'] = product_id
        
        # 创建商品对象
        category = product_data.get('category', 'electronics')
        if category == 'electronics':
            product = Electronics(**product_data)
        elif category == 'clothing':
            product = Clothing(**product_data)
        elif category == 'books':
            product = Books(**product_data)
        else:
            product = Electronics(**product_data)  # 默认类型
        
        # 保存到文件
        products_data = self.data_manager.load_products()
        products_data.append(product.to_dict())
        
        if self.data_manager.save_products(products_data):
            info(f"Successfully added product: {product.name} (ID: {product_id})")
            return product
        else:
            raise RuntimeError("Failed to save product")
    
    def update_product(self, product_id, update_data):
        """更新商品信息（带验证）"""
        # 验证更新数据
        is_valid, errors = self.validate_product_data(update_data)
        if not is_valid:
            raise ValueError("; ".join(errors))
        
        products_data = self.data_manager.load_products()
        for i, product_data in enumerate(products_data):
            if product_data['product_id'] == product_id:
                # 更新数据
                products_data[i].update(update_data)
                
                if self.data_manager.save_products(products_data):
                    info(f"Successfully updated product: {product_id}")
                    return True
                else:
                    raise RuntimeError("Failed to save product update")
        
        raise ValueError(f"Product does not exist: {product_id}")
    
    def get_product_reviews(self, product_id):
        """获取商品的所有评价
        
        Args:
            product_id: 商品ID
            
        Returns:
            list: 评价列表
        """
        try:
            # 获取评价服务
            from core.services.review_service import ReviewService
            review_service = ReviewService()
            
            # 获取所有评价
            all_reviews = review_service.get_all_reviews()
            
            # 筛选该商品的评价
            product_reviews = [review for review in all_reviews if review.product_id == product_id]
            
            return product_reviews
            
        except Exception as e:
            error(f"Failed to get product reviews: {e}")
            return []
    
    def get_product_rating_stats(self, product_id):
        """获取商品评分统计
        
        Args:
            product_id: 商品ID
            
        Returns:
            dict: 包含平均评分、总评价数、各星级数量等统计信息
        """
        try:
            reviews = self.get_product_reviews(product_id)
            
            if not reviews:
                return {
                    'average_rating': 0.0,
                    'total_reviews': 0,
                    'rating_distribution': {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
                }
            
            # 计算平均评分
            total_rating = sum(review.rating for review in reviews)
            average_rating = total_rating / len(reviews)
            
            # 统计各星级数量
            rating_distribution = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
            for review in reviews:
                rating_distribution[review.rating] += 1
            
            return {
                'average_rating': round(average_rating, 1),
                'total_reviews': len(reviews),
                'rating_distribution': rating_distribution
            }
            
        except Exception as e:
            error(f"Failed to get product rating statistics: {e}")
            return {
                'average_rating': 0.0,
                'total_reviews': 0,
                'rating_distribution': {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
            }